#!/bin/bash
# 此脚本用来编译安装sratoolkit-3.0.0软件
# sratoolkit软件介绍
#   sratoolkit用于sra文件处理的软件包。
#  Usage:
#     bash /path/to/build.sh /path/to/build /path/to/install
# 使用build.sh 脚本样例 bash /path/to/build.sh /path/to/build /path/to/install
# 使用build.sh 需要root权限或者sudo权限,否则无法安装依赖
#
##############################################################
set -e

source "$(
  cd "$(dirname "$0")" || exit 1
  pwd
)/common.sh"

function write_sratoolkit_run() {
  cat >"$1/sratoolkit-3.0.0-hpc/run.sh" <<EOF
#!/bin/bash
yum install -y wget tar git environment-modules libatomic flex bison-devel glibc-devel libstdc++-static make perl cmake openssl fuse-devel libxml2-devel file-devel patch
source /etc/profile &> /dev/null 
current_dir="\$(cd "\$(dirname "\${BASH_SOURCE[0]}")" && pwd -P)"
for f in "\${current_dir}"/*; do
  if [[ -d "\${f}" && -f "\$(ls "\${f}"/*modulefiles 2>&1)" ]]; then
    module use "\${f}" && module load "\${f}"/*modulefiles
  fi
done 
echo -e "\033[1;32;1msratoolkit environment initialization completed.\033[0m"
EOF

  chmod +x "$1"/sratoolkit-3.0.0-hpc/run.sh
}

function install_kunpeng-gcc() {
  bash "$1"/kunpeng-gcc-10.3.1.sh "$2" "$3"
  module use "$3"/kunpeng-gcc-10.3.1
  module load "$3"/kunpeng-gcc-10.3.1/kunpeng-gcc_modulefiles
}

function install_ncbi-vdb() {
  bash "$1"/ncbi-vdb-3.0.0.sh "$2" "$3"
  module use "$3"/ncbi-vdb-3.0.0
  module load "$3"/ncbi-vdb-3.0.0/ncbi-vdb_modulefiles
}

function install_sratoolkit() {
  bash "$4"/sratoolkit-3.0.0.sh "$1" "$2"
  mkdir -p "$3"/sratoolkit-3.0.0-hpc && cp -r "$2"/* "$3"/sratoolkit-3.0.0-hpc/
}

function tar_pkg() {
  echo "# 正在打包sratoolkit文件 路径为$1"
  cd "$1" && tar zcvf sratoolkit-3.0.0-hpc.tar.gz sratoolkit-3.0.0-hpc
  echo -e "\033[1;32;1m# sratoolkit已经打包成功 文件路径为$1/sratoolkit-3.0.0-hpc.tar.gz\033[0m"
}

function install_development() {
  yum install -y m4 environment-modules systemd-devel 
  source /etc/profile
  module purge
}

function main() {
  is_check_build_install_directory "$1" "$2" "build.sh"
  buildpath=$(create_dir "$1")
  installpath=$(create_dir "$2")
  dep_dir=$(get_current_dir)/dependency
  pkg_dir=$(get_current_dir)/pkg
  install_development
  install_kunpeng-gcc "$dep_dir" "$buildpath" "$installpath"
  install_ncbi-vdb "$dep_dir" "$buildpath" "$installpath"
  install_sratoolkit "$buildpath" "$installpath" "$pkg_dir" "$(get_current_dir)"
  write_sratoolkit_run "$pkg_dir"
  tar_pkg "$pkg_dir"
  echo "# ------------------------------------------------------------------------"
  echo "# 运行软件前请执行以下命令"
  echo -e "\033[1;32;1m# source ""${pkg_dir}""/sratoolkit-3.0.0-hpc/run.sh\033[0m"
  echo "# 来加载sratoolkit运行时环境变量"
  echo "# ------------------------------------------------------------------------"
  rm -rf "$buildpath" "$installpath"
}

main "$@"
